//
//  ConsultViewController.m
//  Toyohu
//
//  Created by celia on 16/3/24.
//  Copyright (c) 2016年 celia. All rights reserved.
//

#import "ProfessorViewController.h"
#import "GPSearchBar.h"

#import "GPAFNetworking3.h"
#import "ProfessorTableViewCell.h"
#import "ProfessorModel.h"
#import <YYModel.h>
#import "ProfessorDetailViewController.h"

#import "LrdSuperMenu.h"
#import <MJRefresh.h>
#import "TYH_LoginLoginModel.h"

#define WIDTH self.view.bounds.size.width
#define HEIGHT self.view.bounds.size.height


static NSString *ProfessorReuseId = @"ProfessorTableViewCell";
@interface ProfessorViewController ()<LrdSuperMenuDataSource, LrdSuperMenuDelegate,UITableViewDelegate,UITableViewDataSource>
{
    UITableView *myTableView;
    NSMutableArray *dataArray;
    
    NSArray *leftItem;
    NSArray *centerItem;
    NSArray *rightItem;
    NSMutableArray *idleImages;
    NSString *myString;
    NSString *leftStr;
    NSString *middleStr;
    NSString *rightStr;
    NSString *title;
    NSString *urlString;
}

@property (nonatomic, strong) LrdSuperMenu *menu;

//@property (nonatomic, strong) DropdownMenu *dropdownMenu;
@end

@implementation ProfessorViewController

-(void)viewWillAppear:(BOOL)animated
{
    [myTableView.mj_header beginRefreshing];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    dataArray = [NSMutableArray array];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [self initSearchBar];
    [self CreateTableView];
    
    [self setupDropdownMenu];
}

-(void)CreateTableView
{
    myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 110, WIDTH, HEIGHT-110-49) style:UITableViewStylePlain];
    myTableView.delegate = self;
    myTableView.dataSource = self;
    [myTableView registerNib:[UINib nibWithNibName:@"ProfessorTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:ProfessorReuseId];
    myTableView.showsVerticalScrollIndicator = NO;
    myTableView.showsHorizontalScrollIndicator = NO;
    myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    myTableView.estimatedRowHeight = 100.0f;
    myTableView.rowHeight = UITableViewAutomaticDimension;
    [self.view addSubview:myTableView];
    
    idleImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=17; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%lu", (unsigned long)i]];
        [idleImages addObject:image];
    }
    
    MJRefreshGifHeader *rightheader = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // 设置普通状态的动画图片
    [rightheader setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
    [rightheader setImages:idleImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    [rightheader setImages:idleImages forState:MJRefreshStateRefreshing];
    // 设置header
    myTableView.mj_header = rightheader;
    rightheader.lastUpdatedTimeLabel.hidden = YES;
    rightheader.stateLabel.hidden = YES;
    rightheader.ignoredScrollViewContentInsetTop = -5;
    
}

-(void)loadNewData
{
    [self getExperts];
}


- (void)initSearchBar
{
    
    GPSearchBar *searchBar = [[GPSearchBar alloc] initWithPlaceholder:@"搜索专家" frame:CGRectMake(0, 0, 4*WIDTH/5, 40) search:^(NSString *str) {
        
        if (dataArray){
            [dataArray removeAllObjects];
            [myTableView reloadData];
        }
        myString = str;
        
        if (str.length > 0) {
            [GPAFNetworking3 get:[NSString stringWithFormat:@"%@?name=%@",GetExpertByName,[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] progress:^(NSProgress * _Nonnull progress) {
                
            } success:^(id  _Nonnull responseObject) {
                for (NSDictionary*myDict in responseObject[@"msg"])
                {
                    ProfessorModel *model = [[ProfessorModel alloc]init];
                    [model yy_modelSetWithDictionary:myDict];
                    [dataArray addObject:model];
                    [myTableView reloadData];
                    
                }
            } failure:^(NSString * _Nonnull errorLD) {
                
            }];
            [searchBar.searchBar resignFirstResponder];
            
        }else{
            
        }
    }];
    
    searchBar.tag = 101;
    searchBar.backgroundColor = [UIColor clearColor];
    self.navigationItem.titleView = searchBar;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [((GPSearchBar*)self.navigationItem.titleView).searchBar  resignFirstResponder];
}


- (void)setupDropdownMenu {
    
   
    leftItem = @[@"擅长领域",@"亲子关系",@"亲子阅读",@"儿童艺术",@"儿童美术",@"早期教育",@"英语启蒙"];
    
    centerItem = @[@"年龄段",@"0到3岁",@"3到6岁",@"6到9岁",@"9到12岁"];
    
    rightItem = @[@"专家排序",@"人气"];
    
    
    
    _menu = [[LrdSuperMenu alloc] initWithOrigin:CGPointMake(0, 64) andHeight:44];
    _menu.delegate = self;
    _menu.dataSource = self;
    [self.view addSubview:_menu];
    
    
}

- (NSInteger)numberOfColumnsInMenu:(LrdSuperMenu *)menu {
    return 3;
}

- (NSInteger)menu:(LrdSuperMenu *)menu numberOfRowsInColumn:(NSInteger)column {
    if (column == 0) {
        return leftItem.count;
    }else if(column == 1) {
        return centerItem.count;
    }else {
        return rightItem.count;
    }
}

- (NSString *)menu:(LrdSuperMenu *)menu titleForRowAtIndexPath:(LrdIndexPath *)indexPath {
    if (indexPath.column == 0) {
        return leftItem[indexPath.row];
    }else if(indexPath.column == 1) {
        return centerItem[indexPath.row];
    }else {
        return rightItem[indexPath.row];
    }
}

- (NSString *)menu:(LrdSuperMenu *)menu imageNameForRowAtIndexPath:(LrdIndexPath *)indexPath {
    if (indexPath.column == 0 || indexPath.column == 1) {
        return @"baidu";
    }
    return nil;
}

//- (NSString *)menu:(LrdSuperMenu *)menu imageForItemsInRowAtIndexPath:(LrdIndexPath *)indexPath {
//    if (indexPath.column == 0 && indexPath.item >= 0) {
//        return @"baidu";
//    }
//    return nil;
//}

- (NSString *)menu:(LrdSuperMenu *)menu detailTextForRowAtIndexPath:(LrdIndexPath *)indexPath {
    if (indexPath.column < 2) {
        return [@(arc4random()%1000) stringValue];
    }
    return nil;
}

//- (NSString *)menu:(LrdSuperMenu *)menu detailTextForItemsInRowAtIndexPath:(LrdIndexPath *)indexPath {
//    return [@(arc4random()%1000) stringValue];
//}


- (void)menu:(LrdSuperMenu *)menu didSelectRowAtIndexPath:(LrdIndexPath *)indexPath {
    
    static NSString *prediStr1 = @"SELF LIKE '*'";
    //NSString *title = [menu titleForRowAtIndexPath:indexPath];
    
    if (dataArray){
        [dataArray removeAllObjects];
        [myTableView reloadData];
    }
    if (indexPath.column==0)
    {
        title = leftItem[indexPath.row];
        urlString = [NSString stringWithFormat:@"%@?speciality=%@&page=1",GetExperts,[title stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    else if (indexPath.column==1)
        
    {
        NSArray *centerArray = @[@"0_3",@"0_3",@"3_6",@"6_9",@"9_12"];
        title = centerArray[indexPath.row];
        urlString = [NSString stringWithFormat:@"%@?age=%@&page=1",GetExperts,title];
    }
    else
    {
        title = rightItem[indexPath.row];
        urlString = [NSString stringWithFormat:@"%@?order=%@&page=1",GetExperts,[title stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    
    [GPAFNetworking3 get:urlString progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(id  _Nonnull responseObject) {
        for (NSDictionary*myDict in responseObject[@"msg"])
        {
            ProfessorModel *model = [[ProfessorModel alloc]init];
            [model yy_modelSetWithDictionary:myDict];
            [dataArray addObject:model];
            [myTableView reloadData];
           
        }
    } failure:^(NSString * _Nonnull errorLD) {
        
    }];
    
    if (indexPath.row == 0) {
        prediStr1 = @"SELF LIKE '*'";
    } else {
        prediStr1 = [NSString stringWithFormat:@"SELF CONTAINS '%@'", title];
    }
    
    [myTableView reloadData];
}


- (void)dropdownSelectedLeftIndex:(NSString *)left RightIndex:(NSString *)right {
   
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    myTableView.rowHeight=113;
    ProfessorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ProfessorReuseId];
    if (!cell) {
        cell = (ProfessorTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: ProfessorReuseId];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.model = dataArray[indexPath.row];
    
    
   
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProfessorDetailViewController*VC = [[ProfessorDetailViewController alloc]init];
    ProfessorModel*model = dataArray[indexPath.row];
    VC.eID = model.eId;
//    [self presentViewController:VC animated:YES completion:nil];
    [self.navigationController pushViewController:VC animated:YES];
}

-(void)getExperts
{
    [GPAFNetworking3 get:GetExperts progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(id  _Nonnull responseObject) {
        TYH_LoginLoginModel *model = [[TYH_LoginLoginModel alloc] initWithDictionary:responseObject];
        
        if (model.code != 1) {
            SHOW_ERROR
        }else{
            [dataArray removeAllObjects];
            for (NSDictionary*myDict in responseObject[@"msg"])
            {
                
                
                ProfessorModel *model = [[ProfessorModel alloc]init];
                [model yy_modelSetWithDictionary:myDict];
                [dataArray addObject:model];
                [myTableView reloadData];
                [myTableView.mj_header endRefreshing];
                
            }
        }
        
    } failure:^(NSString * _Nonnull errorLD) {
        SHOW_NTERROR
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
